package InterviewTest.q0206_isPalindrome;

import CommonClass.Common.ListNode;

public class Solution {
    /*
    与234相同的题
    1 首先用快慢指针找出中点
    2 分割中点 然后使后一半链表倒转
    3 然后分别从两端开始比较节点值是否相同即可 链表的奇偶对此没有影响 因为奇数时中点会因为长度不同被忽略
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) return true;
        // 1 快慢指针
        ListNode slow = head, fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // 2 倒转链表
        ListNode pre = null, cur = slow.next;
        slow.next = null;

        while (cur.next != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        cur.next = pre;

        // 3 对比差异
        while (head != null && cur != null) {
            if (head.val != cur.val) return false;
            head = head.next;
            cur = cur.next;
        }

        return true;
    }
}
